#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Name: Fanfou in Python / PyFan
# Visit http://code.google.com/p/pyfan

__author__ = 'ppip.nk@gmail.com'
__version__ = '0.0.7'

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

import getopt
import cPickle
import os.path
import imp

import fanfou
import gui

def usage():
    print '''* PyFan / Fanfou in Python *
* Writen by ppip (ppip.nk@gmail.com) *

Usage:
    At the first run, you should give me a username to set up the database:

        pyfan -l username

    Then you can post like this, password will be asking at the first time:

        pyfan [[Options] what you want to talk]

    If nothing is giveing, it will print timeline.
    You can use following options:

    -l username
    --user=username
        Give the working username, if not used before, it will setup a
        new database. ( use --max=number to set number to download)
    -u
    --update
        Update the datebase.

    -n num
    --number=num
        Print out number of post list from recently (default: 20).
    -b number
    --begin=number
        Set the begin post of print out list (default: 1).

    -t
    --timeline
        print out all talks in your database(use with -n and -b).
    -m
    --me
        Print @me posts.
    -c friendname
    --conversation=friendname
        Print out conversation between you and your friend.

    -w username
    --who=username
        Print out timeline of the user.
    -s string
    --search=string
        Search what user said by the string.
    -d date
    --date=date
        Search by date, divide by 2 number, like 0801252304 means "2008, Jan, 
        23, 23:04". In short term, "08" means all posts in 2008 and "0801" 
        means all posts in 2008 Jan, etc. Use "00" (use 24/60 for hour/min) 
        if you do not want limit it, "00000022" means all the post write at 
        22pm in the night.

        NOTE: -w, -s, -d is based on last list that print out.

    -f number
    --favorite=number
        Add to favorite by the list number. (The number last print out)
    -D number
    --delete=number
        Delete the post by the list number. (The number last print out)

    -P number
    --purge=number
        Purge the oldest posts in the timeline.

    -h
    --help
        Print this text.
    -V
    --version
        Print out version
    ...
'''

def main(argv):

    version =  __version__  #Version of the program

    # Get the running path
    if hasattr(sys, "frozen") or imp.is_frozen("__main__"):
        selfpath = os.path.abspath(os.path.dirname(sys.executable))
    else:
        selfpath = os.path.abspath(os.path.dirname(sys.argv[0]))

    try:
        opts, args = getopt.gnu_getopt(argv, "l:tn:b:Vhumc:s:d:w:f:D:P:", \
            ["user=", "timeline", "number=", "begin=", \
            "version", "help", "update", "me", "conversation=", \
            "search=", "date=", "who=", "favorite=", "max=", \
            "delete=", "purge=", "gui"])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    # worklist to save the working list (generate by searching, etc)
    worklist = []
    username = ""
    for o, a in opts:
        if o in ("-l", "--user"):
            username = a 
    if username == "":
        try:
            # Read data from file
            hander = file(os.path.join(selfpath, "pyfan.conf"), "r")
            username = cPickle.load(hander)
            worklist = cPickle.load(hander)
        except IOError:
            usage()
            sys.exit(2)

    max = 100
    for o, a in opts:
        if o == "--max":
             max = int(a)
    work = fanfou.Api(username, maxnumber = max)

    for o, a in opts:
        if o == "--gui":
            pyfan_gui = gui.Gui(work)

    if worklist == []:
        worklist = work.list

    if opts == [] and args == []:
        work.timeline()

    b = 1
    n = 20
    for o, a in opts:
        if o in ("-b", "--begin"):
            b = int(a)
        if o in ("-n", "--number"):
            n = int(a)

    for o, a in opts:
        if o in ("-u", "--update"):
            work.update()
	    worklist = work.list
        if o in ("-t", "--timeline"):
            work.timeline(n, b)
	    worklist = work.list

        if o in ("-c", "--conversation"):
            worklist = work.find_conversation(a)
            work.print_list(worklist, number = n, starts = b)
        if o in ("-m", "--me"):
            worklist = work.find_post_to_me()
            work.print_list(worklist, number = n, starts = b)

        if o in ("-s", "--search"):
            worklist = work.find_post_by_string(worklist, a)
            work.print_list(worklist, number = n, starts = b)
        if o in ("-d", "--date"):
            year = 0; mon = 0; day = 0; hour = -1; min = -1
            if len(a) >= 2:
                if a[:2] != "00":
                     year = int("20"+a[:2])
                if len(a) >= 4:
                    if a[2:4] != "00":
                        mon = int(a[2:4])
                    if len(a) >= 6:
                        if a[4:6] != "00":
                            day = int(a[4:6])
                        if len(a) >= 8:
                            if int(a[6:8]) < 23:
                                hour = int(a[6:8])
                            if len(a) >= 10:
                                if int(a[8:10]) < 60:
                                    min = int(a[8:10])
            worklist = work.find_post_by_date(worklist, year, mon, day, hour, min)
            work.print_list(worklist, number = n, starts = b)
        if o in ("-w", "--who"):
            worklist = work.who(worklist, a)
            work.print_list(worklist, number = n, starts = b)
            
        if o in ("-f", "--favorite"):
            if int(a) <= len(worklist) + 1:
	        work.print_list([worklist[int(a)-1]], number = 1)
                str = worklist[int(a)-1][1]
                work.favorite(str)
            else:
	            print "Out of range."
        if o in ("-D", "--delete"):
            if int(a) <= len(worklist) + 1:
                work.print_list([worklist[int(a)-1]], number = 1)
                if worklist[int(a)-1][3] == work.user:
                    temp = worklist.pop(int(a)-1)
                    try:
                        work.list.remove(temp)
                    except:
                        pass
                    str = temp[1]
                    work.delete(str)
                else:
                    print "Not your post."
            else:
                print "Out of range."
        if o in ("-P", "--purge"):
            work.purge(int(a))
        if o in ("-h", "--help"):
            usage()
        if o in ("-V", "--version"):
            print "Version: ", version

    if len(args) != 0:
        p = " ".join(args)
        work.post(p)

    # save the config data
    hander = file(os.path.join(selfpath, "pyfan.conf"), "w")
    cPickle.dump(username, hander, 0)
    if len(worklist) == len(work.list):
        worklist = []
    cPickle.dump(worklist, hander, 0)
    hander.close()

    # Delete the fanfou class to force it save the data
    del(work)
    sys.exit(0)

if __name__ == "__main__":
    main(sys.argv[1:])
